<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      title="根据销售单导入"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <PageForm
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          />
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <NewPageFilter :filter-btn="filterInfo.btnList">
            <template v-slot:filter-productCodeScan>
              <ScanInputBox
                v-model:query="scanInfo.query"
                :table-data="tableInfo.data"
                :api="scanInfo.api"
                :get-product-ids="scanInfo.getProductIds"
                @callback="onCallBackScanData"
              />
            </template>
            <template v-slot:filter-removeProduct>
              <el-button
                :disabled="!tableInfo.selections.length"
                @click="removeProduct"
                >删除</el-button
              >
            </template>
          </NewPageFilter>
          <div>
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :tab-index="false"
                :check-box="true"
                :isRowClickSelect="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :merge-data="tableInfo.mergeData"
                :merge-filed="tableInfo.mergeFiled"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-licenseNumber="scope">
                  <p>{{ scope.row.licenseNumber || '-' }}</p>
                  <p>{{ scope.row.brandName || '-' }}</p>
                </template>
                <template v-slot:col-commonName="scope">
                  <p>{{ scope.row.commonName || '-' }}</p>
                  <p>{{ scope.row.productCode || '-' }}</p>
                  <p>{{ scope.row.alias || '-' }}</p>
                </template>
                <template v-slot:col-type="scope">
                  <p>{{ scope.row.productTypeValue || '-' }}</p>
                  <p>{{ scope.row.codeTypeValue || '-' }}</p>
                  <p>{{ scope.row.productCategoryValue || '-' }}</p>
                </template>
                <template v-slot:col-standard="scope">
                  <p>{{ scope.row.standard || '-' }}</p>
                  <p>{{ scope.row.unitName || '-' }}</p>
                </template>
                <template v-slot:col-calcUnitName="scope">
                  <p>{{ scope.row.calcUnitName || '-' }}</p>
                  <p>{{ scope.row.unitConvertCoefficient || '-' }}</p>
                </template>
                <template v-slot:col-sterilizationNumber="scope">
                  <el-input v-model="scope.row.sterilizationNumber"></el-input>
                </template>
                <template v-slot:col-qty="scope">
                  <el-form-item
                    v-if="scope.row.codeType !== 3"
                    class="margin-bottom"
                  >
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              v-model.lazy="scope.row.largeUnitQty"
                              style="width: 100%"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                              @change="
                                changeLarge(
                                  $event,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                          class="page-table-input-number-item"
                        >
                          <el-form-item>
                            <el-input-number
                              v-model.lazy="scope.row.smallUnitQty"
                              style="width: 100%"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="scope.row.unitConvertCoefficient - 1"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        v-if="scope.row.qtyOperateMode === 2"
                        class="page-table-input-number-right"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                  <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                </template>
                <template v-slot:col-price="scope">
                  <el-form-item
                    :prop="'data.' + scope.$index + '.price'"
                    :rules="[
                      {
                        required: scope.$index >= 0,
                        message: '请输入结算单价',
                        trigger: 'blur',
                      },
                    ]"
                  >
                    <el-input-number
                      v-model="scope.row.price"
                      :precision="systemConfig.price_precision"
                      :max="999999999999999"
                      controls-position="right"
                      :min="0"
                    ></el-input-number>
                    <p
                      style="color: red"
                      v-if="
                        scope.row.isLimitPrice == 1 &&
                        scope.row.price > scope.row.purchaseLimitPrice
                      "
                    >
                      超过产品限价:{{ scope.row.purchaseLimitPrice }}
                    </p>
                  </el-form-item>
                </template>
                <template v-slot:col-batchNumber="scope">
                  <el-input
                    v-if="scope.row.codeType !== 3"
                    v-model="scope.row.batchNumber"
                    :maxlength="25"
                    @input="(e) => (scope.row.batchNumber = validSe(e))"
                  />
                  <span v-else>{{ scope.row.batchNumber || '-' }}</span>
                </template>
                <template v-slot:col-productionDate="scope">
                  <el-date-picker
                    v-if="scope.row.codeType !== 3"
                    v-model="scope.row.productionDate"
                    value-format="YYYY-MM-DD"
                    :disabled-date="productionTimePickerOptions.disabledDate"
                  />
                  <span v-else>{{ scope.row.productionDate || '-' }}</span>
                </template>
                <template v-slot:col-validityDate="scope">
                  <el-date-picker
                    v-if="scope.row.codeType !== 3"
                    v-model="scope.row.validityDate"
                    value-format="YYYY-MM-DD"
                    :disabled-date="validityTimePickerOptions.disabledDate"
                  />
                  <span v-else>{{ scope.row.validityDate || '-' }}</span>
                </template>
              </PageTable>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <AddProduct
      v-if="productInfo.visible"
      v-model:query="productInfo.query"
      v-model:show-dialog="productInfo.visible"
      @callback="selectProduct"
    />
    <Individual
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      :info="individualInfo.data"
      @individualBack="individualBack"
    ></Individual>
  </div>
</template>
<script setup name="deliverOrderModify">
import AddProduct from './addProduct'
import ScanInputBox from './ScanInputBox'
import Individual from './individual'
import _ from 'lodash'
import {
  getDeliverDetailBySaleId,
  addDeliverOrder,
  getDeliverOrderById,
  updateDeliverOrder,
  mergeDeliverOrderDetail,
  deliverOrderScan,
} from '@/api/supplier.js'

const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'saleOrderId', 'orderId'])
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const productionTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() > Date.now() - 8.64e6
  },
})
const validityTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() < Date.now()
  },
})
const scanInfo = ref({
  query: {
    saleId: '',
    hospitalId: '',
    // isConsignment: "",
  },
  api: deliverOrderScan,
  getProductIds: [],
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
const formInfo = ref({
  ref: null,
  data: {
    hospitalId: '',
    expectedDeliverTime: '',
    deptId: '',
  },
  fieldList: [
    {
      label: '客户',
      value: 'hospitalName',
      type: 'input',
      disabled: true,
    },
    {
      label: '客户部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '预计发货日期',
      value: 'expectedDeliverTime',
      type: 'date',
      dateType: 'date',
      valueFormat: 'YYYY-MM-DD',
      TimePickerOptions: {
        // 限制收货时间不让选择今天以前的
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        },
      },
    },
    {
      label: '收货人',
      value: 'receiveContacts',
      type: 'input',
      disabled: true,
    },
    {
      label: '收货电话',
      value: 'receivePhone',
      type: 'input',
      disabled: true,
    },
    {
      label: '收货地址',
      value: 'receiveAddress',
      type: 'input',
      disabled: true,
    },
    { label: '发票号码', value: 'invoiceNumber', type: 'input' },
    { label: '货单号码', value: 'waybillNumber', type: 'input' },
    {
      label: '创建人',
      value: 'createUserName',
      type: 'input',
      disabled: true,
    },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'input',
      disabled: true,
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '是否暂估入库',
      value: 'isEstimationStockBusiness',
      type: 'select-model',
      code: 'default_no_or_yes',
      disabled: false,
      checkDefault: false,
      event: 'isEstimationStockBusiness',
      show:
        proxy.$store.state.permission.systemConfig
          .is_estimation_stock_business == 1,
    },
    {
      label: '配送方式',
      value: 'deliveryType',
      type: 'select-model',
      code: 'delivery_type',
      clearable: true,
    },
    {
      label: '配送人',
      value: 'deliveryUser',
      type: 'input',
    },
    {
      label: '配送人电话',
      value: 'deliveryPhone',
      type: 'input',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    expectedDeliverTime: [
      { required: true, message: '请选择发货日期', trigger: 'blur' },
    ],
    receivePhone: [{ validator: proxy.$validate.cellphone, trigger: 'blur' }],
  },
  labelWidth: '120px',
})
const isUpdate = ref(true)
// 过滤相关配置
const filterInfo = ref({
  query: {
    saleId: props.saleOrderId,
  },
  btnList: [
    {
      type: 'button',
      label: '添加产品',
      event: addProduct,
    },
    {
      type: 'slot',
      label: '删除产品',
      value: 'removeProduct',
    },
    {
      type: 'slot',
      value: 'productCodeScan',
    },
  ],
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  mergeData: {},
  mergeFiled: [
    'licenseNumber',
    'commonName',
    'type',
    'standard',
    'calcUnitName',
    'deliverableQty',
  ],
  fieldList: [
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      type: 'slot',
      minWidth: 220,
    },
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      type: 'slot',
      minWidth: 220,
    },
    {
      label: '产品类型\n条码类型',
      value: 'type',
      type: 'slot',
      minWidth: 150,
    },
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
    { label: '计算单位\n转换系数', value: 'calcUnitName', type: 'slot' },
    {
      label: '是否寄售',
      value: 'isConsignmentValue',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '可发数量数',
      value: 'deliverableQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '发货数量',
      value: 'qty',
      type: 'slot',
      width: 250,
    },
    {
      label: '生产批号',
      value: 'batchNumber',
      type: 'slot',
    },
    {
      label: '生产日期',
      value: 'productionDate',
      type: 'slot',
      width: 160,
    },
    {
      label: '失效日期',
      value: 'validityDate',
      type: 'slot',
      width: 160,
    },
    {
      label: '结算单价',
      value: 'price',
      type: 'slot',
      width: 148,
    },
    {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },

    {
      label: '灭菌批号',
      value: 'sterilizationNumber',
      type: 'input',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '160',
    btList: [
      {
        label: '添加批号',
        event: addBatchNumber,
        show: true,
        ifRender: function (row) {
          return row.codeType !== 3
        },
      },
      {
        label: '个体操作',
        event: individual,
        show: true,
        ifRender: function (row) {
          return row.codeType === 3 && row.details && row.details.length
        },
      },
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const productInfo = ref({
  visible: false,
  query: {
    saleId: '',
    deliverId: '',
    productIdNotIn: [],
    isConsignment: '',
  },
})
const individualInfo = ref({
  visible: false,
  index: '',
  data: {},
})
const formRefs = ref(null)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        row['calcQty'] = calcQty
        row['sumAmount'] = proxy.$fn.accDiv(
          proxy.$fn.accMul(row.calcQty, row.price || 0),
          unitConvertCoefficient
        )

        if (!row.flag) {
          row['qty'] = qty
        }
      })
      tableInfo.value.mergeData = proxy.$fn.getMergeData(val)
      scanInfo.value.getProductIds = []
      val.forEach((item) => {
        scanInfo.value.getProductIds.push(item.productId)
      })
    } else {
      scanInfo.value.getProductIds = []
    }
  },
  { deep: true }
)

function showTableFieldListItem(show, nameValue) {
  let fieldList = tableInfo.value.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.hidden = show
    }
  })
}
function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.deliverableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.deliverableQty
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChioce) {
    return 'success-row'
  } else {
    return ''
  }
}
function onCallBackScanData(obj) {
  obj.data.isConsignBusiness = formInfo.value.data.isConsignBusiness
  if (tableInfo.value.data.length) {
    tableInfo.value.data.forEach((item) => {
      item.isChioce = false
      if (item.details && item.details.length) {
        item.details.forEach((row) => {
          row.isChioce = false
        })
      }
    })
  }
  if (obj.flag === 1) {
    let data = obj.data
    data.details = [proxy.$fn.deepClone(data)]
    data.factoryMainCode = ''
    data.factorySubCode = ''
    data.flag = true
    data.gs1Code = ''
    tableInfo.value.data[obj.index] = data
  } else if (obj.flag === 2) {
    let item = tableInfo.value.data[obj.index]
    let data = obj.data
    item.isChioce = true
    item.details.unshift(data)
    item.calcQty = proxy.$fn.accAdd(item.calcQty, data.calcQty || 0)
    item.qty = proxy.$fn.accAdd(item.qty, data.qty || 0)
    item.largeUnitQty = proxy.$fn.accAdd(
      item.largeUnitQty,
      data.largeUnitQty || 0
    )
    item.smallUnitQty = proxy.$fn.accAdd(
      item.smallUnitQty,
      data.smallUnitQty || 0
    )
    item.sumAmount = proxy.$fn.accAdd(
      item.sumAmount,
      proxy.$fn.accDiv(
        proxy.$fn.accMul(data.price || 0, data.calcQty || 0),
        data.unitConvertCoefficient || 1
      )
    )
  } else if (obj.flag === 3) {
    let data = obj.data
    data.details = [proxy.$fn.deepClone(data)]
    data.factoryMainCode = ''
    data.factorySubCode = ''
    data.flag = true
    data.gs1Code = ''
    data.isChioce = true
    tableInfo.value.data.unshift(data)
    //发货单新增页使用合并,根据productId大小排序
    let spanArr = tableInfo.value.data.concat([])
    tableInfo.value.data = spanArr.sort(compare('productId'))
  }
  proxy.$message({
    message: `扫码成功`,
    type: 'success',
    duration: 3500,
    showClose: true,
  })

  proxy.$forceUpdate()
}
function compare(property) {
  return function (a, b) {
    return a[property] - b[property]
  }
}
function individual(row, index) {
  individualInfo.value.data = row
  individualInfo.value.index = index
  individualInfo.value.visible = true
}
function individualBack(data) {
  let item = tableInfo.value.data[individualInfo.value.index]
  if (data.length) {
    let largeUnitQty = 0
    let smallUnitQty = 0
    let qty = 0
    data.forEach((item) => {
      largeUnitQty = proxy.$fn.accAdd(item.largeUnitQty, largeUnitQty)
      smallUnitQty = proxy.$fn.accAdd(item.smallUnitQty, smallUnitQty)
      qty = proxy.$fn.accAdd(item.qty, qty)
    })
    item.largeUnitQty = largeUnitQty
    item.smallUnitQty = smallUnitQty
    item.qty = qty
    tableInfo.value.data[individualInfo.value.index].details = data
  } else {
    item.largeUnitQty = 0
    item.smallUnitQty = 0
    item.qty = 0
    item.calcQty = 0
    item.sumAmount = 0
    item.flag = false
    delete item.details
  }
}
function save() {
  if (
    formInfo.value.data.isEstimationStockBusiness == 1 &&
    formInfo.value.data.isConsignBusiness == 1
  ) {
    proxy.$message.warning('是否寄售和是否暂估入库只能二选一！')
    return
  }
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api = undefined
    if (props.saleOrderId) {
      api = addDeliverOrder
    } else if (props.orderId) {
      api = updateDeliverOrder
    }
    let details = proxy.$fn.deepClone(tableInfo.value.data)
    if (!details.length) {
      proxy.$message({
        message: '请添加产品',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let detailsList = details
      .filter((item) => item.calcQty <= 0 || !item.calcQty)
      .map((item) => item.commonName)
    if (detailsList.length) {
      proxy.$alert(`产品【${detailsList}】你还未处理`, '操作提示', {
        confirmButtonText: '确定',
      })
      return
    }
    const needBatchNumberProduct = details
      .filter(
        (detail) =>
          detail.needBatchNumber == 1 &&
          ((!detail.batchNumber && detail.batchNumber !== '0') ||
            !detail.productionDate ||
            !detail.validityDate)
      )
      .map((detail) => detail.commonName)
    if (needBatchNumberProduct.length) {
      proxy.$alert(
        `请输入产品【${needBatchNumberProduct}】的批号效期`,
        '操作提示',
        {
          confirmButtonText: '确定',
        }
      )
      return
    }
    if (!checkSumDate(details)) return
    if (!checkSameBatch(details)) return
    if (!getSameCodeQty(_.groupBy(details, 'productCode'))) return
    const params = {
      ...formInfo.value.data,
      mergeDetails: proxy.$fn.filterBlacklist(details),
    }
    if (
      !formInfo.value.data.invoiceNumber ||
      !formInfo.value.data.waybillNumber
    ) {
      proxy
        .$confirm('你的发票号或货单号为空，是否继续提交？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
        .then(() => {
          api(params).then((res) => {
            if (res && res.success) {
              proxy.$emit('returnModify')
              showDialog.value = false
            }
          })
          return
        })
        .catch(() => {
          return
        })
    } else {
      api(params).then((res) => {
        if (res && res.success) {
          proxy.$emit('returnModify')
          showDialog.value = false
        }
      })
    }
  })
}
function getSameCodeQty(data) {
  let arr = []
  let values = Object.values(data)
  values.forEach((items) => {
    let needNum = 0
    let num = 0
    items.forEach((item) => {
      needNum = item.deliverableCalcQty
      num = proxy.$fn.accAdd(num, item.calcQty)
    })
    if (num > needNum) {
      arr.push(items[0].commonName)
    }
  })
  if (arr.length) {
    proxy.$message({
      message: `产品【${arr}】发货数量大于可发货数量，请修改`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return false
  }
  return true
}
function checkSumDate(data) {
  let checkSumDataList = []
  data.forEach((item) => {
    if (item.validityDate) {
      if (judgeTime(item.validityDate) >= 0) {
        checkSumDataList.push(`${item.commonName}`)
      }
    }
  })
  if (checkSumDataList.length > 0) {
    let str = checkSumDataList.join(',')
    proxy.$message({
      message: `产品【${str}】存在失效日期小于当前日期，请修改`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return false
  }
  return true
}
function judgeTime(data) {
  var d1 = new Date(data)
  var dd = new Date()
  var y = dd.getFullYear()
  var m = dd.getMonth() + 1
  var d = dd.getDate()
  var d2 = new Date(y + '-' + m + '-' + d)
  var iday = parseInt(d2 - d1) / 1000 / 60 / 60 / 24
  return iday
}
function checkSameBatch(data) {
  let checkSameBatchIndex = []
  for (let item of data) {
    const filter = data.filter((item1) => {
      return (
        item1.productCode +
          '&' +
          item1.batchNumber +
          '&' +
          item1.productionDate +
          '&' +
          item1.validityDate ===
        item.productCode +
          '&' +
          item.batchNumber +
          '&' +
          item.productionDate +
          '&' +
          item.validityDate
      )
    })
    if (filter.length > 1) {
      checkSameBatchIndex.push(`${item.commonName}`)
      break
    }
  }
  if (checkSameBatchIndex.length > 0) {
    let str = checkSameBatchIndex.join(',')
    proxy.$message({
      message: `产品【${str}】存在相同批号效期，请修改`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return false
  }
  return true
}
function addBatchNumber(row) {
  const index = tableInfo.value.data.findIndex((item) => item === row)
  tableInfo.value.data.splice(index, 0, {
    ...row,
    batchNumber: '',
    productionDate: '',
    validityDate: '',
    sterilizationNumber: '',
    id: Math.random(),
    qty: 0,
    calcQty: 0,
  })
}
function addsterilizeNum(row) {
  if (!row.batchNumber) {
    proxy.$message({
      message: '请先输入该行的生产批号',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  const index = tableInfo.value.data.findIndex((item) => item === row)
  tableInfo.value.data.splice(index, 0, {
    ...row,
    batchNumber: row.batchNumber || '',
    sterilizationNumber: '',
    productionDate: row.productionDate || '',
    validityDate: row.validityDate || '',
  })
}
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
function addProduct() {
  productInfo.value.visible = true
  let ids = tableInfo.value.data.map((item) => {
    return item.productId
  })
  productInfo.value.query.isConsignment = formInfo.value.data.isConsignBusiness
  productInfo.value.query.saleId = formInfo.value.data.saleId
  productInfo.value.query.deliverId = formInfo.value.data.id
  productInfo.value.query.productIdNotIn = ids.toString()
}
function selectProduct(rows) {
  rows.forEach((item) => {
    if (item.codeType === 3) {
      item.flag = false
    }
  })
  tableInfo.value.data = rows.concat(tableInfo.value.data)
}
function getSaleMain() {
  getDeliverDetailBySaleId(props.saleOrderId).then((res) => {
    if (res && res.success) {
      let data = res.data
      if (data.mergeDetails.length) {
        data.mergeDetails.forEach((item) => {
          if (item.codeType === 3) {
            item.flag = false
          }
          item.sterilizationNumber = ''
        })
        tableInfo.value.data = data.mergeDetails
      }
      formInfo.value.data = res.data
      scanInfo.value.query.saleId = res.data.saleId
      scanInfo.value.query.hospitalId = res.data.hospitalId
      // scanInfo.value.query.isConsignment = res.data.isConsignBusiness;
    }
  })
}
function getMain() {
  getDeliverOrderById(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.value.data = res.data
      scanInfo.value.query.saleId = res.data.saleId
      scanInfo.value.query.deliverId = res.data.id
      scanInfo.value.query.hospitalId = res.data.hospitalId
      // scanInfo.value.query.isConsignment = res.data.isConsignBusiness;
    }
  })
}
function getList() {
  mergeDeliverOrderDetail({ orderId: props.orderId }).then((res) => {
    if (res && res.success) {
      if (res.data.length) {
        res.data.forEach((item) => {
          if (item.codeType === 3) {
            item.flag = true
          }
        })
      }
      let spanArr = res.data.concat([])
      spanArr.sort(compare('productId'))

      tableInfo.value.data = spanArr
    }
  })
}

onMounted(() => {
  if (props.saleOrderId) {
    getSaleMain()
  } else if (props.orderId) {
    getMain()
    getList()
  }
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
})
</script>
